<template>
  <CardDialog v-model:visible="show" width="1000px" :title="`${form.policyId ? '编辑' : '新增'}策略`">
    <div class="form-content">
      <div class="form-left">
        <a-form class="dialog-form" ref="formRef" :model="form" :rules="rules" :label-col="{ span: 8 }">
          <a-form-item label="策略名称" name="policyName">
            <a-input style="width: 100%" v-model:value="form.policyName" placeholder="请输入策略名称" />
          </a-form-item>
          <a-form-item label="是否启用" name="isEnabled">
            <a-switch
              v-model:checked="form.isEnabled"
              checked-children="启用"
              un-checked-children="禁用"
              :checkedValue="true"
              :unCheckedValue="false"
            />
          </a-form-item>
          <a-form-item label="策略类型" name="policyType">
            <a-select
              v-model:value="form.policyType"
              style="width: 100%"
              placeholder="请选择策略类型"
              :options="policyTypeList"
              :fieldNames="{ label: 'name', value: 'value', options: 'options' }"
            />
          </a-form-item>
          <a-form-item label="所属大桥" name="bridgeId">
            <a-select ref="select" v-model:value="form.bridgeId" style="width: 100%" placeholder="请选择所属大桥">
              <a-select-option v-for="item in bridgeList" :key="item.bridgeId" :value="item.bridgeId">
                {{ item.bridgeName }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="关联区域" name="areaIds">
            <a-select
              v-model:value="form.areaIds"
              mode="multiple"
              style="width: 100%"
              placeholder="请选择关联区域"
              max-tag-count="responsive"
              :options="areaList"
              :fieldNames="{ label: 'areaName', value: 'areaId', options: 'options' }"
              @change="areaIdsChange"
            />
          </a-form-item>
          <!-- 超速报警 -->
          <a-form-item label="超速报警" name="isSpeedAlarm">
            <a-switch
              v-model:checked="form.isSpeedAlarm"
              checked-children="开启"
              un-checked-children="关闭"
              :checkedValue="true"
              :unCheckedValue="false"
            />
          </a-form-item>
          <div v-if="form.isSpeedAlarm">
            <a-form-item label="最大速度" name="maxSpeed">
              <a-input style="width: 100%" v-model:value="form.maxSpeed" placeholder="请输入最大速度" />
            </a-form-item>
            <a-form-item label="最小速度" name="minSpeed">
              <a-input style="width: 100%" v-model:value="form.minSpeed" placeholder="请输入最小速度" />
            </a-form-item>
          </div>
          <!-- 超高报警 -->
          <a-form-item label="超高报警" name="isHeightAlarm">
            <a-switch
              v-model:checked="form.isHeightAlarm"
              checked-children="开启"
              un-checked-children="关闭"
              :checkedValue="true"
              :unCheckedValue="false"
            />
          </a-form-item>
          <div v-if="form.isHeightAlarm">
            <a-form-item label="安全高度" name="safeHeight">
              <a-input style="width: 100%" v-model:value="form.safeHeight" placeholder="请输入安全高度" />
            </a-form-item>
            <a-form-item label="水位计最低高度" name="clearanceHeight">
              <a-input style="width: 100%" v-model:value="form.clearanceHeight" placeholder="请输入桥梁与水位计最低高度" />
            </a-form-item>
          </div>
          <!-- 偏航 -->
          <a-form-item label="偏航报警" name="isYaw">
            <a-switch v-model:checked="form.isYaw" checked-children="开启" un-checked-children="关闭" :checkedValue="true" :unCheckedValue="false" />
          </a-form-item>
          <!-- 卡口字段 -->
          <div v-if="form.policyType === '2'">
            <a-form-item label="上行角度" name="climbCourse">
              <a-input style="width: 100%" v-model:value="form.climbCourse" placeholder="请输入上行角度" />
            </a-form-item>
            <a-form-item label="下行角度" name="descentCourse">
              <a-input style="width: 100%" v-model:value="form.descentCourse" placeholder="请输入下行角度" />
            </a-form-item>
            <a-form-item label="角度误差" name="differenceCourse">
              <a-input style="width: 100%" v-model:value="form.differenceCourse" placeholder="请输入角度误差" />
            </a-form-item>
          </div>
        </a-form>
      </div>
      <div class="form-right" v-if="show">
        <MapCard class="map-card" ref="mapRef" />
      </div>
    </div>
    <div class="button-list">
      <a-button class="form-button" type="primary" @click="onSubmit">保存</a-button>
      <a-button class="form-button form-button-cancel" type="primary" @click="onClose">取消</a-button>
      <a-button class="form-button form-button-cancel" type="primary" @click="resetForm">重置</a-button>
    </div>
  </CardDialog>
</template>
<script setup>
  import { reactive, nextTick, ref } from 'vue';
  import _ from 'lodash';
  import { message } from 'ant-design-vue';
  import { SmartLoading } from '/@/components/framework/smart-loading';
  import { smartSentry } from '/@/lib/smart-sentry';
  import CardDialog from '/@/components/cardDialog/index.vue';
  import MapCard from '/@/components/map/index.vue';
  import { api } from '/@/api/plat/policy.js';
  import { policyTypeList, alarmTypeList } from '/@/config/strategy.js';

  const props = defineProps({
    bridgeList: {
      type: Array,
      default: () => [],
    },
    areaList: {
      type: Array,
      default: () => [],
    },
  });
  const emits = defineEmits(['onload']);
  let show = ref(false);
  const mapRef = ref();
  const formRef = ref();
  const formDefault = {
    policyId: undefined,
    policyName: undefined,
    isEnabled: false,
    policyType: undefined,
    areaIds: [],
    isCapture: false,
    isRecord: false,
    isLifejacket: false,
    isSpeed: false,
    maxSpeed: undefined,
    minSpeed: undefined,
    safeHeight: undefined,
    isDrift: false,
    isAis: false,
    bridgeId: undefined,
    isHeightAlarm: undefined,
    isSpeedAlarm: undefined,
    clearanceHeight: undefined,
    isYaw: undefined,
  };
  const rules = {
    policyName: [{ required: true, message: '请填写策略名称' }],
    isEnabled: [{ required: true, message: '请选择是否启用' }],
    policyType: [{ required: true, message: '请选择策略类型' }],
    bridgeId: [{ required: true, message: '请选择所属大桥' }],
    areaIds: [{ required: true, message: '请选择关联区域' }],
    alarmType: [{ required: true, message: '请选择报警类型' }],
    maxSpeed: [{ required: true, message: '请填写最大速度' }],
    minSpeed: [{ required: true, message: '请填写最小速度' }],
    maxHeight: [{ required: true, message: '请填写最大高度' }],
    minHeight: [{ required: true, message: '请填写最小高度' }],
    climbCourse: [{ required: true, message: '请填写上行角度' }],
    descentCourse: [{ required: true, message: '请填写下行角度' }],
    differenceCourse: [{ required: true, message: '请填写角度误差' }],
    safeHeight: [{ required: true, message: '请填写安全高度' }],
    clearanceHeight: [{ required: true, message: '请填写桥梁与水位计最低高度' }],
  };
  let form = ref({ ...formDefault });

  function getClickCoordinate(val) {
    form.value.longitude = val[0].toFixed(6);
    form.value.latitude = val[1].toFixed(6);
  }

  function open(rowData) {
    form.value = { ...formDefault };
    if (rowData && !_.isEmpty(rowData)) {
      form.value = Object.assign({}, form.value, rowData);
    }
    show.value = true;
    nextTick(() => {
      mapRef.value.initMainMap();
      // 如果有区域的话，就画一下区域
      if (form.value.policyId) {
        areaIdsChange(form.value.areaIds);
      }
    });
  }

  function areaIdsChange(areaIds) {
    const list = props.areaList.filter((m) => areaIds.includes(m.areaId));
    if (list.length > 0) {
      mapRef.value.drawAreas(list);
    }
  }

  function resetForm() {
    form.value = Object.assign({}, formDefault);
    formRef.value.resetFields();
  }

  function onClose() {
    resetForm();
    show.value = false;
  }

  async function onSubmit() {
    try {
      await formRef.value.validateFields();
      save(form.value);
    } catch (err) {
      message.error('参数验证错误，请仔细填写表单数据!');
    }
  }

  // 新建、编辑API
  async function save(formData) {
    SmartLoading.show();
    try {
      let result = null;
      if (formData.policyId) {
        result = await api.update(formData);
      } else {
        result = await api.add(formData);
      }
      if (result && result.data) {
        message.success('保存成功');
        onClose();
        emits('onload');
      } else {
        message.error('保存失败');
      }
    } catch (err) {
      smartSentry.captureError(err);
    } finally {
      SmartLoading.hide();
    }
  }

  defineExpose({
    open,
  });
</script>

<style lang="less" scoped>
  @import '/@/assets/style/form.less';
  .form-content {
    height: 60vh;
    display: grid;
    grid-template-columns: 40% 60%;
    padding: 0 0 10px;
    .form-left {
      padding: 5px 0 0;
      overflow-y: scroll;
      overflow-x: hidden;
    }
    ::-webkit-scrollbar {
      width: 8px;
    }
    ::-webkit-scrollbar-track {
      background: #2f6e90;
    }
    ::-webkit-scrollbar-thumb {
      background-color: rgba(0, 0, 0, 0.2);
      border-radius: 4px;
    }
    ::-webkit-scrollbar-thumb:hover {
      background-color: rgba(0, 0, 0, 0.4);
    }
    .form-right {
      padding-right: 5px;
      position: relative;
      > .map-card {
        border: 2px solid #1d77c4;
        border-radius: 3px;
        cursor: pointer;
      }
      .form-right-tips {
        position: absolute;
        z-index: 1;
        top: 2px;
        left: 2px;
        background-color: #333b;
        color: #fff;
        padding: 10px 15px;
        border-radius: 0 0 20px 0;
      }
    }
  }
  .button-list {
    padding: 10px 0;
    display: flex;
    align-items: center;
    justify-content: center;
    .form-button {
      margin: 0 10px;
    }
    .form-button-cancel {
      background-color: #ccc;
      color: #000;
      &:hover {
        background-color: #eee;
      }
    }
  }
</style>
